package com.qf.listener.simple;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @RabbitListener 指定要要监听的队列名称
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/10 22:12
 * description:
 */
@Component
@RabbitListener(queues = "simple_queue" )
public class SimpleQueueListener {

    @Autowired
    StringRedisTemplate redisTemplate;

    @RabbitHandler
    public  void  consum(String msg, Channel channel, Message message){

        String messageId = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        //setIfAbsent： 判断是否存在key，如果存在key，则什么都不做,返回false
        //如果key不存在，相当于set操作，返回true
        //key： messageid  value：0
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(messageId, "0");
        //如果并不存在。正常消费
        if(flag){
            System.out.println("消费者消费:"+msg);
            //消费完成后，修改状态为1
            redisTemplate.opsForValue().set(messageId, "1",1, TimeUnit.MINUTES);
            //手动ack
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //删除redis中的messageId信息
            redisTemplate.delete(messageId);
        }
        //返回false，说明返回此messageid存在
        else {
            String value= redisTemplate.opsForValue().get(messageId);
            //如果value，说明消费成功，则直接手动ack（确认已经消费）
            if("1".equalsIgnoreCase(value)){
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                redisTemplate.delete(messageId);
            }
            //如果value为0，说明正在消费



        }

    }
}
